<template>
    <BasicLayout>
        <template #wrapper>
            <el-card class="box-card">
                <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px" v-if="false">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable size="small"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="简介" prop="about">
                        <el-input v-model="queryParams.about" placeholder="请输入简介" clearable size="small"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <el-form-item label="是否免费" prop="isFree">
                        <el-select v-model="queryParams.isFree" placeholder="是否免费" clearable size="small">
                            <el-option v-for="dict in isFreeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                :value="dict.dictValue" />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="课程状态" prop="locked">
            <el-select
              v-model="queryParams.locked"
              placeholder="课程状态"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in lockedOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->

                    <el-form-item label="状态" prop="status">
                        <el-select v-model="queryParams.status" placeholder="课程状态" clearable size="small">
                            <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                :value="dict.dictValue" />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:service:add']" type="primary" icon="el-icon-plus" size="mini"
                            @click="handleAdd" v-if="courseType == 'classCourse'">新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:service:edit']" type="success" icon="el-icon-edit" size="mini"
                            :disabled="single" @click="handleUpdate">修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:service:remove']" type="danger" icon="el-icon-delete"
                            size="mini" :disabled="multiple" @click="handleDelete">删除
                        </el-button>
                    </el-col>
                </el-row>

                <el-table v-loading="loading" :data="educourseList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="课程封面" align="center" prop="cover" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-avatar :size="50" :src="scope.row.cover"></el-avatar>
                        </template>
                    </el-table-column>
                    <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" />

                    <el-table-column label="简介" align="center" prop="about" :show-overflow-tooltip="true" />
                    <el-table-column label="点击量" align="center" prop="hitNum" :show-overflow-tooltip="true" />
                    <el-table-column label="是否免费" align="center" prop="isFree" :formatter="isFreeFormat" width="100">
                        <template slot-scope="scope">
                            {{ isFreeFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="原价" align="center" prop="originPrice" :show-overflow-tooltip="true" />
                    <el-table-column label="现价" align="center" prop="price" :show-overflow-tooltip="true" />
                    <el-table-column label="vip价" align="center" prop="vipPrice" :show-overflow-tooltip="true" />

                    <el-table-column label="连载方式" align="center" prop="serializeMode" :formatter="serializeModeFormat"
                        width="100">
                        <template slot-scope="scope">
                            {{ serializeModeFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" width="100">
                        <template slot-scope="scope">
                            {{ statusFormat(scope.row) }}
                        </template>
                    </el-table-column>

                    <el-table-column label="课时总数" align="center" prop="lessonNum" :show-overflow-tooltip="true" />
                    <el-table-column label="课程状态" align="center" prop="locked" :formatter="lockedFormat" width="100">
                        <template slot-scope="scope">
                            {{ lockedFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="笔记数" align="center" prop="noteNum" :show-overflow-tooltip="true" />
                    <el-table-column label="课时发布数量" align="center" prop="publishLessonNum"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="问题数" align="center" prop="questionNum" :show-overflow-tooltip="true" />
                    <el-table-column label="课程计划评分" align="center" prop="rating" :show-overflow-tooltip="true" />
                    <el-table-column label="课程计划评论数" align="center" prop="ratingNum" :show-overflow-tooltip="true" />
                    <el-table-column label="学员数" align="center" prop="studentNum" :show-overflow-tooltip="true" />
                    <el-table-column label="话题数" align="center" prop="threadNum" :show-overflow-tooltip="true" />
                    <el-table-column label="操作" align="center" fixed="right" width="180"
                        class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <!-- <el-button
                                v-permisaction="['edu:service:edit']"
                                size="mini"
                                type="text"
                                icon="el-icon-s-promotion"
                                @click="handleUpdate(scope.row)"
                                >发布
                            </el-button> -->
                            <el-button v-permisaction="['edu:service:edit']" size="mini" type="text" icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">修改
                            </el-button>
                            <el-button v-permisaction="['edu:service:remove']" size="mini" type="text"
                                icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                            </el-button>
                            <el-dropdown @command="handleCommand($event, scope.row)">
                                <span class="el-dropdown-link">
                                    更多<i class="el-icon-arrow-down el-icon--right"></i>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item command="posting">发布课程</el-dropdown-item>
                                    <el-dropdown-item command="market">营销设置</el-dropdown-item>
                                    <el-dropdown-item command="course">课时管理</el-dropdown-item>
                                    <el-dropdown-item command="teacher">教师管理</el-dropdown-item>
                                    <el-dropdown-item command="classmate">学员管理</el-dropdown-item>
                                    <el-dropdown-item command="dateView">数据概览</el-dropdown-item>
                                    <el-dropdown-item command="order">订单统计</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageIndex"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />

                <!-- 添加或修改对话框 -->
                <el-dialog :title="title" :visible.sync="open" width="500px">
                    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                        <el-form-item label="课程封面" prop="cover">
                            <uploadImg :imgUrl.sync="form.cover"></uploadImg>
                        </el-form-item>

                        <el-form-item label="标题" prop="title">
                            <el-input v-model="form.title" placeholder="标题" />
                        </el-form-item>

                        <el-form-item label="简介" prop="about">
                            <el-input type="textarea" :rows="5" placeholder="请输入简介" v-model="form.about"></el-input>
                        </el-form-item>

                        <el-form-item label="连载方式" prop="serializeMode">
                            <el-radio-group v-model="form.serializeMode">
                                <el-radio v-for="dict in serializeModeOptions" :key="dict.dictValue"
                                    :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="是否免费" prop="isFree">
                            <el-switch v-model="form.isFree" active-value="T" inactive-value="F"></el-switch>
                        </el-form-item>

                        <el-form-item label="原价" prop="originPrice" v-if="form.isFree == 'F'">
                            <el-input-number v-model="form.originPrice" :precision="2" :step="0.1" :min="0">
                            </el-input-number>
                        </el-form-item>
                        <el-form-item label="现价" prop="price" v-if="form.isFree == 'F'">
                            <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0"></el-input-number>
                        </el-form-item>

                        <el-form-item label="vip价格" prop="vipPrice" v-if="form.isFree == 'F'">
                            <el-input-number v-model="form.vipPrice" :precision="2" :step="0.1" :min="0">
                            </el-input-number>
                        </el-form-item>

                        <!-- <el-form-item label="课程状态" prop="locked">
              <el-radio-group v-model="form.locked">
                <el-radio
                  v-for="dict in lockedOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item> -->

                        <el-form-item label="课程评分" prop="rating">
                            <el-rate v-model="form.rating" show-score></el-rate>
                        </el-form-item>
                        <el-form-item label="点击量" prop="hitNum">
                            <el-input-number v-model="form.hitNum" placeholder="点击量"></el-input-number>
                        </el-form-item>

                        <el-form-item label="权重" prop="weigh">
                            <el-input-number v-model="form.weigh" placeholder="权重"></el-input-number>
                        </el-form-item>

                        <el-form-item label="发布状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">
                                    {{ dict.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
                <!-- 营销设置 -->
                <market :courseId="courseId" :drawer.sync="drawer"></market>
                <!-- 课时设置 -->
                <lesson :courseId="courseId" :drawer.sync="drawer"></lesson>
                <!-- 教师管理 -->
                <teacher :courseId="courseId" :drawer.sync="drawer"></teacher>
                <!-- 学员管理 -->
                <classmate :courseId="courseId" :drawer.sync="drawer"></classmate>
                <!-- 班级添加课程 -->
                <el-dialog title="添加课程" class="dialogForm" :visible.sync="showClassCourse"
                    :before-close="dialogBeforeClose">
                    <el-table :data="schCourseList" style="width: 100%" @selection-change="selectCourse">
                        <el-table-column type="selection" width="55" align="center">
                        </el-table-column>
                        <el-table-column label="课程名称" width="width">
                            <template slot-scope="scope">
                                <div class="row ali_cen">
                                    <el-avatar :size="50" :src="scope.row.cover" style="margin-right:10px"></el-avatar>
                                    <span>{{ scope.row.title }}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="studentNum" label="学员数量" width="width">
                        </el-table-column>
                        <el-table-column prop="originPrice" label="价格" width="width">
                        </el-table-column>
                    </el-table>
                    <pagination v-show="course_total > 0" :total="course_total" :page.sync="course_param.pageIndex"
                        :limit.sync="course_param.pageSize" @pagination="getSchoolCourseList" />
                    <div slot="footer">
                        <el-button @click="dialogBeforeClose">取 消</el-button>
                        <el-button type="primary" @click="addClassCourse">确 定</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </template>
    </BasicLayout>
</template>

<style lang="scss" scoped>
.dialogForm {
    display: block;
    .el-dialog {
        margin-top: 15vh !important;
    }
}
.flip-list-move {
    transition: transform 0.5s;
}

.no-move {
    transition: transform 0s;
}

.ghost {
    opacity: 0.1;
    background: #eee;
}

.list-group {
    min-height: 20px;
    border-left: 2px solid #f1f1f1 !important;
}
.line {
    height: 2px;
    background: #fafafa;
    -webkit-user-select: none; /* 禁止 DIV 中的文本被鼠标选中 */
    -moz-user-select: none; /* 禁止 DIV 中的文本被鼠标选中 */
    -ms-user-select: none; /* 禁止 DIV 中的文本被鼠标选中 */
    user-select: none;
}

.list-group-item {
    cursor: move;
    padding: 0 24px;
    width: 100%;
    height: 56px;
    line-height: 56px;
    background: #fafafa !important;
    border-radius: 6px;
}
.list-group-item i {
    cursor: pointer;
}
.wrapper {
    display: flex;
    justify-content: center;
    width: 100%;
}
.item {
    width: 300px;
    height: 50px;
    background-color: #42b983;
    color: #ffffff;
}
.content {
    padding: 0 20px;
    .courseBox {
        padding: 20px;
        border-radius: 6px;
        border: 1px solid #ddd;
    }
}
.taskBox {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    width: 95%;
    box-sizing: border-box;
}
.freeTask {
    color: #fff;
    background-color: #f46300;
}
.taskItem .el-checkbox__label {
    width: 100%;
}
.el-dropdown-link {
    cursor: pointer;
    color: #409eff;
    font-size: 12px;
    margin-left: 10px;
}
.el-icon-arrow-down {
    font-size: 12px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<script>
import {
    addEduCourse,
    delEduCourse,
    getEduCourse,
    listEduCourse,
    updateEduCourse,
    putChapter,
    postChapter,
    postSort,
    delChapter,
    chapterList
} from "@/api/edu/service";
import {
    teacherCourseList,
    schoolCourseList,
    addClassCourse
} from "@/api/edu/teacherCourse";
import classmate from "../components/classmate.vue";
import lesson from "../components/lesson.vue";
import market from "../components/market.vue";
import teacher from "../components/teacher.vue";
import { getToken } from "@/utils/auth";
export default {
    name: "Config",
    components: {
        classmate,
        lesson,
        market,
        teacher
    },

    data () {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            isEdit: false,
            // 类型数据字典
            typeOptions: [],
            educourseList: [],
            isFreeOptions: [],
            lockedOptions: [],
            serializeModeOptions: [],
            statusOptions: [],
            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                about: undefined,
                courseId: undefined,
                isFree: undefined,
                locked: undefined,
                originPrice: undefined,
                status: undefined,
                title: undefined
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                about: [
                    { required: true, message: "简介不能为空", trigger: "blur" }
                ],
                courseId: [
                    {
                        required: true,
                        message: "课程ID不能为空",
                        trigger: "blur"
                    }
                ],
                isFree: [
                    { required: true, message: "不能为空", trigger: "blur" }
                ],
                locked: [
                    {
                        required: true,
                        message: "课程状态不能为空",
                        trigger: "blur"
                    }
                ],
                originPrice: [
                    {
                        required: true,
                        message: "课程人民币原价不能为空",
                        trigger: "blur"
                    }
                ],
                status: [
                    {
                        required: true,
                        message: "状态不能为空",
                        trigger: "blur"
                    }
                ],
                title: [
                    { required: true, message: "标题不能为空", trigger: "blur" }
                ]
            },

            //上传
            uploadImageAction:
                process.env.VUE_APP_BASE_API + "/api/v1/common/uploadImage",
            myHeader: {
                Authorization: "Bearer " + getToken()
            },
            // 抽屉类型
            drawer: "",
            courseId: "",
            courseType: "teachCourse",
            showClassCourse: false,
            schoolId: "",
            schCourseList: [],
            courseIds: [],
            course_total: 0,
            course_param: {
                pageIndex: 1,
                pageSize: 10
            }
        };
    },
    watch: {
        showClassCourse (now) {
            if (now) {
                this.getSchoolCourseList();
            }
        }
    },
    created () {
        this.$store.dispatch("tagsView/updateVisitedView", this.$route);
        this.schoolId = this.$route.params.schoolId;
        this.courseType = this.$route.params.teacherId
            ? "teachCourse"
            : "classCourse";

        this.getList();
        this.getDicts("sys_bool").then(response => {
            this.isFreeOptions = response.data;
        });

        this.getDicts("sys_bool").then(response => {
            this.lockedOptions = response.data;
        });

        this.getDicts("edu_serialize_mode").then(response => {
            this.serializeModeOptions = response.data;
        });

        this.getDicts("edu_status").then(response => {
            this.statusOptions = response.data;
        });
    },
    methods: {
        // 班级添加课程
        addClassCourse () {
            console.log(this.courseIds);
            addClassCourse(this.$route.params.classroomId, this.courseIds).then(
                res => {
                    this.dialogBeforeClose();
                    this.getList();
                }
            );
        },
        selectCourse (data) {
            if (data.length) {
                this.courseIds = data.map(item => item.courseId);
            }
        },
        // 获取学校课程
        getSchoolCourseList () {
            schoolCourseList(this.schoolId, this.course_param).then(res => {
                this.schCourseList = res.data.list;
                this.course_total = res.data.count;
            });
        },
        onMove ({ relatedContext, draggedContext }) {
            const relatedElement = relatedContext.element;
            const draggedElement = draggedContext.element;
            return (
                (!relatedElement || !relatedElement.fixed) &&
                !draggedElement.fixed
            );
        },
        // 关闭抽抽屉
        handleClose (done) {
            this.drawer = "";
            // done();
        },
        // 按钮操作
        handleCommand (command, data) {
            this.courseId = data.courseId;
            if (command == "edit") {
                this.handleUpdate(data);
            } else if (command == "del") {
                this.handleDelete(data);
            } else {
                this.drawer = command;
            }
        },
        /** 查询参数列表 */
        getList () {
            this.loading = true;
            teacherCourseList(
                this.$route.params.teacherId
                    ? this.$route.params.teacherId
                    : this.$route.params.classroomId,
                this.addDateRange(this.queryParams, this.dateRange),
                this.$route.params.teacherId ? "teacherInfo" : "classroomInfo"
            ).then(response => {
                this.educourseList = response.data.list;
                this.total = response.data.count;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                about: undefined,
                courseId: undefined,
                cover: undefined,
                hitNum: undefined,
                isFree: undefined,
                lessonNum: undefined,
                locked: undefined,
                noteNum: undefined,
                originPrice: undefined,
                price: undefined,
                publishLessonNum: undefined,
                questionNum: undefined,
                rating: undefined,
                ratingNum: undefined,
                serializeMode: undefined,
                status: undefined,
                studentNum: undefined,
                threadNum: undefined,
                title: undefined,
                vipPrice: undefined,
                weigh: undefined
            };
            this.resetForm("form");
        },
        isFreeFormat (row) {
            return this.selectDictLabel(this.isFreeOptions, row.isFree);
        },
        lockedFormat (row) {
            return this.selectDictLabel(this.lockedOptions, row.locked);
        },
        serializeModeFormat (row) {
            return this.selectDictLabel(
                this.serializeModeOptions,
                row.serializeMode
            );
        },
        statusFormat (row) {
            return this.selectDictLabel(this.statusOptions, row.status);
        },

        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageIndex = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd () {
            if (this.$route.params.classroomId) {
                this.showClassCourse = true;
                return false;
            }
            this.reset();
            this.open = true;
            this.title = "添加课程";
            this.isEdit = false;
        },
        // 关闭添加课程弹窗

        dialogBeforeClose () {
            this.showClassCourse = false;
            this.courseIds = [];
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.courseId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            const courseId = row.courseId || this.ids;
            getEduCourse(courseId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改课程";
                this.isEdit = true;
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.courseId !== undefined) {
                        updateEduCourse(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    } else {
                        addEduCourse(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const Ids = row.courseId || this.ids;
            this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(function () {
                    return delEduCourse(Ids, this.$route.params.classroomId);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () { });
        },

        //图片上传 start

        handleRemove (file, fileList) {
            console.log(file, fileList);
            this.form.cover = "";
            console.log(this.form.cover);
        },

        //上传组图成功
        handlepostingImageSuccess (res, file) {
            console.log(res.data);
            if (res.code == "200") {
                this.form.cover = res.data.url;
            }

            console.log(this.form.avatar);
        },
        beforeAvatarUpload (file) {
            const isJPG = file.type === "image/jpeg";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        }

        //图片上传 end
    }
};
</script>
